package phone.book;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;

import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.extensions.Email;
import com.google.gdata.data.extensions.Name;
import com.google.gdata.data.extensions.PhoneNumber;
import com.google.gdata.util.ServiceException;

public class import_contacts extends ListActivity{

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try {			
			
			//ContentResolver cr = getContentResolver();
			ArrayList<String> names = contains();
			syncAllContacts(names);
			finish();
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void syncAllContacts(ArrayList<String> names)     
	throws ServiceException, IOException {   // Request the feed
		ContactsService myService = new ContactsService("GoogleInc-jsguide-1.0");
		String user = getIntent().getExtras().getString("userName");
		String pass = getIntent().getExtras().getString("pass");
		Log.d("user", user);
        Log.d("pass", pass);
        myService.setUserCredentials(user, pass);
        
		URL feedUrl = new URL("https://www.google.com/m8/feeds/contacts/default/full");
		
		ContactFeed resultFeed = myService.getFeed(feedUrl, ContactFeed.class);   // Print the results
		
		System.out.println(resultFeed.getTitle().getPlainText()); 
		Log.d("Title", resultFeed.getTitle().getPlainText());
		for (ContactEntry entry : resultFeed.getEntries()) 
		{    
			ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
			ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI).withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null).withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).build());                      
			
			if (entry.hasName()) 
			{       
				Name name = entry.getName();       
				if (name.hasFullName()) 
				{         
					String fullNameToDisplay = name.getFullName().getValue();         
					if (name.getFullName().hasYomi()) 
					{           
						fullNameToDisplay += " (" + name.getFullName().getYomi() + ")";         
		
					}	
					if(names.size()>0)
					{
						if(!names.contains(fullNameToDisplay))
						{
							ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, fullNameToDisplay).build());                   
							System.out.println("\t\t" + fullNameToDisplay);
						}
					}
					else
					{
						ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, fullNameToDisplay).build());                  
						
					}
				} 
				else
				{   
					ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, "").build());                   
					System.out.println("\t\t (no full name found)");    
				}   
			} 
			else { 
				ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, "").build());                   
				System.out.println("\t (no name found)");
			}      
		System.out.println("Phone Numbers:");
		
		List<PhoneNumber> nums = entry.getPhoneNumbers();
		if(!nums.isEmpty())
		{
			for(PhoneNumber number : nums)
			{			
				String phonenumber = number.getPhoneNumber();
				System.out.println(" "+number.getPhoneNumber());
				
				if(phonenumber.equalsIgnoreCase(""))
				{
					
					ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, "").withValue(ContactsContract.CommonDataKinds.Phone.TYPE,ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE).build());
					
				}
				else
				{
					
					ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phonenumber).withValue(ContactsContract.CommonDataKinds.Phone.TYPE,ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE).build());
				}
				System.out.print("\n");
			}
		}
		else
		{
			
			ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, "").withValue(ContactsContract.CommonDataKinds.Phone.TYPE,ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE).build());
		
		}
		
		System.out.println("Email addresses:");     
		for (Email email : entry.getEmailAddresses())
		{       
						String mail = email.getAddress();
						System.out.print(" " + email.getAddress());
						ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.Email.DATA, mail).withValue(ContactsContract.CommonDataKinds.Email.TYPE,ContactsContract.CommonDataKinds.Email.TYPE_HOME).build());                     
			
		}      
		try                      
		{   	
			
			getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
		
		}                      
		catch (Exception e)                      
		{                                        
			e.printStackTrace();                         
		} 
	
		
	  } 
		Intent i=new Intent(getApplicationContext(),PhonebookActivity.class);
		startActivityForResult(i, 0);
		
	}
	private ArrayList<String> contains() {
		
		ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,    null, null, null, null);
        ArrayList<String> nlist = new ArrayList<String>();
        if (cur.getCount() > 0) {
	        
        	while (cur.moveToNext()) {
        		 String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));           
                 nlist.add(name);                
        	}
        	return nlist;
        	}
        return null;
	}
	
	
}
